<template>
	<view class="pay-page">
		<bnn-loading :loading="isLoading" />
		<scroll-view class="pay-body">
			<view class="time-select">
				<view class="section-title">选择订阅时长</view>
				<view class="price-list d-f j-c-b f-w-w">
					<view v-for="(item, key) in priceList" :key="key" class="price"
						:class="{'active': priceInfo.id === item.id}" @click="switchPayTime(item, key)">
						<view class="pay-amount">
							<view class="month">{{item.effective_time}}{{item.type==0?'天':'个月'}}</view>
							<view class="cash">
								{{item.pay_type==1?'￥'+item.price * item.effective_time:item.price * item.effective_time / 100+'积分'}}
							</view>
						</view>
						<view class="cash-monthly">
							<view class="yuan" v-if="item.pay_type==1">￥</view>
							<view class="yuan" v-else>
								<u-icon name="integral"></u-icon>
							</view>
							<view class="amount">{{item.pay_type==1?item.price:item.price/100}}</view>
							<view class="unit">/{{item.type==0?'天':'月'}}</view>
						</view>
						<view class="origin-price">
							{{ item.pay_type==1?'原价￥'+item.original_price * item.effective_time:item.original_price * item.effective_time/100+'积分'}}
						</view>
						<view class="origin-time">有效期:{{getLocalTime(item.deadline)}}</view>
						<view class="slw-icon select-icon">&#xe6a6;</view>
					</view>
				</view>
			</view>
			<view class="option-list">
				<view class="list-item" @click="setOpenCoupon(true)">
					<view class="item-left">优惠券</view>
					<view class="item-right d-f a-i-c">
						<view class="coupon-name">{{couponInfo.name}}</view>
						<view class="slw-icon">&#xe733;</view>
					</view>
				</view>
			</view>
			<view class="option-list">
				<view class="list-item" @click="setOpenpay(true)">
					<view class="item-left">支付方式</view>
					<view class="item-right d-f a-i-c">
						<view class="coupon-name" v-if="typeKey==0">微信支付</view>
						<view class="coupon-name" v-if="typeKey==2">积分支付</view>
						<view class="slw-icon">&#xe733;</view>
						<!-- <view class="coupon-name" v-if="typeKey==0">支付宝丫</view> -->
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="pay-foot">
			<view class="h-line" />
			<view class="foot-body d-f j-c-b">
				<view class="total d-f a-i-c">
					<view class="total-amount">{{typeKey==2?payAmount/100+'积分':'￥'+payAmount}}</view>
					<!-- <view class="total-amount">{{payAmount}}</view> -->
				</view>
				<view class="btn-subscribe d-f a-i-c j-c-c" @click="onPayNow">立即支付</view>
			</view>
		</view>
		<bnn-float-layout :isShow="isOpenpay" scrollY title='支付方式' class="coupon-float" @close="setOpenpay(false)">
			<view class="pay-method">
				<block v-if="onlyIntegral">
					<view v-for="(type, key) in typeList" :key="key" class="method" @click="switchPayType(key)">
						<view class="h-line" />
						<view class="method-info">
							<view class="method-left">
								<view class="slw-icon method-icon" :style="{color: type.color}" v-html="type.icon" />
								<view>{{type.name}}</view>
							</view>
							<view class="method-right">
								<view class="slw-icon select-icon" :class="{'active': typeKey === key}">&#xe656;</view>
								<view class="slw-icon select-icon" :class="{'active': typeKey !== key}">&#xe6d7;</view>
							</view>
						</view>
					</view>
				</block>
				<!-- 添加 -->
				<view class="method" v-if="isintegral" @click="switchPayType(2)">
					<view class="h-line" />
					<view class="method-info">
						<view class="method-left">
							<!-- <view class="slw-icon method-icon" :style="{color: type.color}" v-html="type.icon"/> -->
							<u-icon class="method-icon" name="integral-fill" color="#FFD800"></u-icon>
							<view>积分支付</view>
						</view>
						<view class="method-right">
							<view class="slw-icon select-icon" :class="{'active': typeKey === 2}">&#xe656;</view>
							<view class="slw-icon select-icon" :class="{'active': typeKey !== 2}">&#xe6d7;</view>
						</view>
					</view>
				</view>
			</view>

		</bnn-float-layout>
		<bnn-float-layout :isShow="isOpenCoupon" scrollY title='优惠券' class="coupon-float" @close="setOpenCoupon(false)">
			<view class="coupon-list">
				<view v-for="(coupon, key) in couponList" :key="key" class="coupon-item" @click="onClickCoupon(coupon)">
					<view class="coupon">
						<view class="coupon-left">
							<image v-if="payAmount >= coupon.min_order_amount"
								src="https://sou-liang.oss-cn-shanghai.aliyuncs.com/weixin/images/my_coupon_active.png"
								class="coupon-img" />
							<image v-else
								src="https://sou-liang.oss-cn-shanghai.aliyuncs.com/weixin/images/my_coupon.png"
								class="coupon-img" />
							<view class="left-content">
								<view class="price">
									<view class="price-unit">￥</view>
									<view class="price-num">{{coupon.amount}}</view>
								</view>
							</view>
						</view>
						<view class="coupon-right">
							<view class="coupon-name">{{coupon.name}}<span class="only-coupon"
									v-if="coupon.for_user === '1' && coupon.strategy_name">仅限【{{coupon.strategy_name}}】使用</span>
							</view>
							<view class="h-line" />
							<view class="time">
								<view class="time-left">{{coupon.expire_time | parseTime('YYYY-MM-DD')}}</view>
								<view class="time-status active">立即使用</view>
							</view>
						</view>
					</view>
				</view>
				<!-- <coupon-empty v-if="couponList.length === 0"/> -->
				<u-empty v-if="couponList.length === 0" text="无优惠券" mode="coupon" icon-size="180" margin-top="70">
				</u-empty>
				<!-- <view  v-if="couponList.length === 0" class="">
					
				</view> -->
			</view>
		</bnn-float-layout>

	</view>
</template>

<script>
	import calc from '@/utils/calc.js'
	import lodash from '@/utils/lodash.js'
	import {
		getOrderInfo,
		integralSubscription
	} from '@/api/order.js'
	import {
		getCouponList,
		createOrder,
		getPaySdk,
		aLiPayConfig,
		weChatPayConfig
	} from '@/api/trade.js'
	import {
		getStrategyInfo
	} from '@/api/strategy.js'
	import BnnFloatLayout from '@/components/bnn-ui/float-layout/index.vue'
	import CouponEmpty from '@/components/data-empty/coupon.vue'
	import BnnLoading from '@/components/bnn-ui/loading/index.vue'
	import {
		toUserStrategyPage
	} from '@/utils/PageRouter.js'
	import {
		parseTime
	} from '@/utils/index.js'

	export default {
		components: {
			BnnFloatLayout,
			CouponEmpty,
			BnnLoading
		},
		data() {
			return {
				id: '',
				isLoading: true,
				isintegral: false,
				onlyIntegral: true,
				strategy: {},
				isOpenCoupon: false,
				isOpenpay: false,
				paytext: '',
				price: 1,
				loading: false,
				providerList: [],
				payAmount: 0,
				couponInfo: {},
				couponList: [],
				typeKey: 0,
				typeList: [{
						id: 'wxpay_js',
						value: 'WECHAT_PAY',
						name: '微信支付',
						icon: '&#xe622;',
						color: '#41b141'
					}
					// { id: 'wxpay_js', value: 'ALI_PAY', name: '支付宝哦', icon: '&#xe618;', color: '#0d99f3' },
				],
				priceInfo: {},
				orderInfo: {},
				priceList: [],
				integralList: [],
				paylist: []
			}
		},
		onLoad(options) {
			this.id = options.id
			this.getStrategy(options.id)
			this.getCoupons()
		},
		onShow() {
			this.getOrderInfo()
		},
		mounted() {

		},
		methods: {
			//选择优惠券
			onClickCoupon(coupon) {
				const {
					payAmount,
					priceInfo
				} = this
				if (payAmount >= coupon.min_order_amount) {
					this.setOpenCoupon(false)
					this.couponInfo = coupon
					this.payAmount = this.calcPayAmount(priceInfo)
				}
			},
			//	获取策略信息
			getStrategy(id) {
				getStrategyInfo({
					id
				}).then(res => {
					const {
						data
					} = res
					if (data.priceList != '') {
						let onlyIntegral = true
						const priceList = data.priceList.map(item => {
							if (item.pay_type == 1) {
								item.price = calc.Div(item.price, 100)
								item.original_price = calc.Div(item.original_price, 100)
								item.amount = calc.Mul(item.effective_time, item.price)
								onlyIntegral = false
							}
							return item
						})
						if (onlyIntegral) this.onlyIntegral = false;
						this.strategy = data
						let num = priceList.length
						for (let i = 0; i < num; i++) {
							if (priceList[i].pay_type == 0) {
								this.isintegral = true
								this.typeKey = 2
								this.integralList.push(priceList[i])
							} else {
								this.typeKey = 0
								this.paylist.push(priceList[i])
							}
						}
						if (this.typeKey == 2) {
							this.priceList = this.integralList
							this.priceInfo = this.integralList[0]
						} else {
							this.priceList = this.paylist
							this.priceInfo = this.paylist[0]
						}
						this.payAmount = this.calcPayAmount(this.priceInfo)
						// #ifdef APP-PLUS
						this.getPayType()
						// #endif
						setTimeout(() => {
							this.isLoading = false
						}, 500)
					}
				})
			},
			//	获取支付方式
			getPayType() {
				uni.getProvider({
					service: "payment",
					success: (e) => {
						let typeList = []
						e.provider.map((id) => {
							switch (id) {
								case 'alipay':
									typeList.push({
										id: id,
										value: 'ALI_PAY',
										name: '支付宝支付',
										icon: '&#xe618;',
										color: '#0d99f3'
									})
									break
								case 'wxpay':
									typeList.push({
										id: id,
										value: 'WECHAT_PAY',
										name: '微信支付',
										icon: '&#xe622;',
										color: '#41b141'
									})
									break
								default:
									break
							}
						})
						this.typeList = typeList
					},
					fail: (e) => {}
				})
			},
			//	获取可使用的优惠券
			getCoupons() {
				getCouponList({
					status: 0,
					strategy_id: this.id
				}).then(res => {
					this.couponList = res.data
				})
			},
			//	获取订单信息
			getOrderInfo() {
				const {
					orderInfo
				} = this
				if (!orderInfo.orderId) {
					return;
				}
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				getOrderInfo(orderInfo.orderId).then(({
					data
				}) => {
					if (data.status === 1) {
						uni.hideLoading()
						uni.showToast({
							mask: true,
							title: "订阅成功！"
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.hideLoading()
					}
				})
			},
			//	(打开、关闭)优惠券弹窗
			setOpenCoupon(bool) {
				this.isOpenCoupon = bool
			},
			setOpenpay(bool) {
				this.isOpenpay = bool
			},
			//	计算支付金额
			calcPayAmount(time) {
				const {
					couponInfo
				} = this
				let amount = calc.Mul(time.effective_time, time.price)
				if (couponInfo.amount) {
					amount = calc.Sub(amount, couponInfo.amount)
				}
				return (amount >= 0 ? amount : 0)
			},
			//	切换支付方式
			switchPayType(key) {
				this.typeKey = key
				this.isOpenpay = false
				if (key == 2) {
					this.priceInfo = this.integralList[0]
					this.payAmount = this.calcPayAmount(this.priceInfo)
					this.priceList = this.integralList
				} else {
					this.priceInfo = this.paylist[0]
					this.payAmount = this.calcPayAmount(this.priceInfo)
					this.priceList = this.paylist
				}
			},
			//	切换购买时长
			switchPayTime(item, key) {
				this.priceInfo = item
				if (item.pay_type == 0) {
					this.typeKey = 2
					this.payAmount = item.price
				} else {
					const {
						couponInfo,
						payAmount
					} = this
					this.couponInfo = (item.amount >= couponInfo.min_order_amount) ? couponInfo : {}
					this.payAmount = this.calcPayAmount(item)
				}

			},
			//	立即付款
			onPayNow() {
				const {
					typeKey,
					typeList
				} = this
				const type = typeList[typeKey]
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				if (this.typeKey == 2) {
					integralSubscription({
						id: this.priceInfo.id
					}).then(res => {
						if (res.code == 200) {
							uni.hideLoading()
							uni.showToast({
								title: "订阅成功！"
							})
							setTimeout(() => {
								uni.navigateBack()
								// 	toUserStrategyPage(true)
							}, 500)
						} else {
							uni.hideLoading()
							uni.showToast({
								title: "积分不足！"
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 500)
						}
					}).catch(err => {
						if (err.code == 200) {
							uni.hideLoading()
							uni.showToast({
								title: "订阅成功！"
							})
							setTimeout(() => {
								uni.navigateBack()
								// 	toUserStrategyPage(true)
							}, 500)
						} else {
							uni.hideLoading()
							uni.showToast({
								title: "积分不足！",
								icon: 'none'
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 500)
						}
					})
				} else {
					//this.createOrder()
					this.miniWeixinPay(); //小程序 微信支付
				}
			},
			
			//小程序 微信支付
			miniWeixinPay() {
				//登录获取用户 的code
				let that = this;
				let openid = uni.getStorageSync('wxopenid')
				that.createOrder(openid) //调用创建订单，并把获取到的openid传过去
			},

			//	创建订单
			createOrder(openid) {
				const {
					id,
					couponInfo,
					priceInfo,
					typeKey,
					typeList,
					payAmount
				} = this
				const pay_type = typeList[typeKey]
				createOrder({
					openid:openid,
					pay_type: pay_type.id,
					strategy_id: id,
					strategy_price_id: priceInfo.id,
					discount_card_id: couponInfo.id
				}).then(res => {
					// 订单创建成功
					const {
						data
					} = res
					this.orderInfo = data
					// uni.hideLoading()
					if (data.isNeedPay) {
						const {
							aliPay
						} = res.data
						this.weixinPay(aliPay)
						
					} else {
						// uni.showToast({ title: "订阅成功！" })
						setTimeout(() => {
							// toUserStrategyPage(true)
							uni.navigateBack()
						}, 500)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			weixinPay(aliPay) {
				const that = this
				try {
					uni.getProvider({
						service: 'payment',
						success: ({
							provider
						}) => {
							// if (~provider.indexOf('wxpay')) {
							// let pay='wxpay'
							if (this.typeKey == 0) {
								uni.hideLoading()
								uni.requestPayment({
									provider: 'wxpay', //alipay
									nonceStr: aliPay.nonce_str,
									package:"prepay_id="+aliPay.prepay_id,
									// partnerid: aliPay.mch_id,
									timeStamp: (aliPay.timestamp)+"",
									paySign: aliPay.sign,
									signType: 'MD5',
									success: function(res) {
										that.getOrderInfo()
									},
									fail: e => {
										uni.showModal({
											content: `微信支付失败`,
											showCancel: false
										})
									}
								})
							}
						},
						fail: e => {
							uni.hideLoading()
							uni.showModal({
								content: `支付失败,原因为: ${e.errMsg}`,
								showCancel: false
							})
						}
					})
				} catch (e) {
					// error
				}

			},
			async requestPayment(e, total) {
				getPaySdk({
					payid: e.id,
					total
				}).then(res => {
			
				}).catch(err => {
					uni.hideLoading()
					if (orderInfo.statusCode !== 200) {
						uni.showModal({
							content: "获得订单信息失败",
							showCancel: false
						})
					}
				})
			},
			getLocalTime(nS) {
				return parseTime(nS)
				// return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');     
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pay-method {
		background-color: #fff;
		height: 100%;

		// .method{
		// 	&:nth-child(1) .method-icon{color: #0d99f3;}
		// 	&:nth-child(2) .method-icon{color: #41b141;}
		// }
		.method-info {
			height: 120rpx;
			padding: 0 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.method-left {
				display: flex;
				align-items: center;
			}

			.method-icon {
				font-size: 64rpx;
				margin-right: 30rpx;
			}

			.select-icon {
				color: #d2d1d1;
				color: $theme_color;
				display: none;
				font-size: 50rpx;
			}

			.active {
				display: block;
			}
		}
	}

	.pay-page {
		/* #ifdef APP-PLUS */
		height: 100vh;
		/* #endif */

		/* #ifndef APP-PLUS */
		// height: calc(100vh - var(--window-top));
		/* #endif */
		position: relative;

		.coupon-float /deep/ {
			.b-f-l__container {
				border-radius: 24rpx 24rpx 0 0;
				background-color: $theme_bg_color;
			}

			.layout-header {
				background-color: $theme_bg_color;
			}

			.coupon-list {
				.coupon-item {
					margin-bottom: 20rpx;

					&:last-child {
						margin-bottom: 0;
					}
				}
			}
		}

		.pay-body {
			width: 100%;
			height: 100%;
			padding: 0 0 50px;
			.time-select {
				background: #fff;
				padding: 0 16px 10px;
				margin-bottom: 10px;
				.section-title {
					color: #666;
					padding: 30rpx 0 20rpx;
				}
				.price-list {
					.price {
						width: 48.5%;
						height: 240rpx;
						border: 1rpx solid #f0f0f0;
						padding: 20rpx 0;
						display: flex;
						position: relative;
						align-items: center;
						border-radius: 4rpx;
						margin-bottom: 30rpx;
						flex-direction: column;
						justify-content: center;

						.pay-amount {
							display: flex;
						}

						.month {
							padding-right: 10rpx;
						}

						.cash-monthly {
							color: #fe6b4f;
							display: flex;
							align-items: baseline;
							line-height: 64rpx;
						}

						.amount {
							font-size: 48rpx;
							padding-right: 10rpx;
						}

						.origin-price {
							color: #999;
							font-size: 20rpx;
							text-decoration: line-through;
						}

						.origin-time {
							font-size: 20rpx;
							color: #999;

						}

						.select-icon {
							color: #ff9954;
							display: none;
							font-size: 48rpx;
							position: absolute;
							right: -2rpx;
							bottom: -2rpx;
						}
					}

					.price.active {
						border-color: #ff9954;
						background: #fff6ef;

						.select-icon {
							display: block;
						}
					}
				}
			}

			.option-list {
				margin-bottom: 20rpx;

				.list-item {
					height: 100rpx;
					padding: 0 30rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					background-color: #fff;
				}
			}


		}

		.pay-foot {
			width: 100%;
			// position: absolute;
			position: fixed;
			bottom: 0;
			background-color: #fff;
		}

		.foot-body {
			height: 100rpx;

			.total {
				padding-left: 40rpx;

				.total-amount {
					color: #ff6600;
					font-size: 40rpx;
				}
			}

			.btn-subscribe {
				color: #fff;
				padding: 0 80rpx;
				background-color: $theme_color;
			}
		}
	}


	.coupon {
		width: 100%;
		height: 170rpx;
		display: flex;

		.coupon-left {
			width: 240rpx;
			position: relative;

			.coupon-img {
				width: 240rpx;
				height: 170rpx;
			}

			.left-content {
				top: 0;
				left: 0;
				height: 100%;
				width: 100%;
				position: absolute;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.price {
				color: #fff;
				display: flex;
				align-items: baseline;

				.price-unit {
					font-size: 32rpx;
					line-height: 1;
					font-weight: bold;
				}

				.price-num {
					font-size: 56rpx;
					line-height: 1;
					font-weight: bold;
				}
			}
		}

		.coupon-right {
			flex: 1;
			height: 100%;
			display: flex;
			flex-direction: column;
			padding-left: 20rpx;
			background-color: #fff;

			.coupon-name {
				flex: 1;
				display: flex;
				align-items: center;
			}

			.only-coupon {
				margin-left: 12rpx;
				font-size: 24rpx;
				color: #999999;
			}

			.time {
				padding: 20rpx 20rpx 20rpx 0;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.time-left {
				color: #999;
				display: flex;
				font-size: 24rpx;
			}

			.time-status {
				color: #fff;
				width: 132rpx;
				height: 40rpx;
				font-size: 22rpx;
				border-radius: 100rpx;
				background-color: #cecece;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.time-status.active {
				background-color: $theme_color;
			}
		}
	}
</style>
